//
//  JDAddAddressViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/5/19.
//

import UIKit

class JDAddAddressViewController: JDBaseViewController {
    
    var addressChangeCallback: ((Bool)->())?

    var contentContainerView: UIView?
    var usernameInputView: UITextField?
    var phoneNumInputView: UITextField?
    
    var selectedAddressInputView: UITextField?
    var selectedAddressControl: UIControl?
    
    var detailAddressInputView: UITextView?
    
    var switchButton: UISwitch?
    var switchTitleLabel: UILabel?
    
    var bottomContainerView: UIView?
    var cancelButton: UIButton?
    var confirmButton: UIButton?
    
    /// 0: 新增 1: 编辑
    var type = 0
    var addressModel: JDAddressModel?
    
    var addressPickerView: JDAddressPickerView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUIElements()
        self.setupConfig()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        if self.type == 1 {
            self.setupNavigationTitle("编辑收货信息")
            self.usernameInputView?.text = self.addressModel?.receiverName
            self.phoneNumInputView?.text = self.addressModel?.mobile
            self.selectedAddressInputView?.text = String.init(format: "%@%@%@", self.addressModel?.province ?? "", self.addressModel?.city ?? "", self.addressModel?.district ?? "")
            self.detailAddressInputView?.text = self.addressModel?.address
            self.switchButton?.isOn = (self.addressModel?.defaultFlag ?? 0) == 1 ? true : false
        } else {
            self.setupNavigationTitle("新增收货信息")
        }
        self.setupLeftBackItem()
    }
    
    func setupUIElements() {
        self.bottomContainerView = UIView()
        self.view.addSubview(self.bottomContainerView!)
        self.bottomContainerView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(104)
        })
        self.bottomContainerView?.backgroundColor = .white

        self.cancelButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.cancelButton!)
        self.cancelButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.bottomContainerView!.snp.centerX).offset(-5)
            make.centerY.equalTo(self.bottomContainerView!)
            make.left.equalTo(self.bottomContainerView!).offset(12)
            make.height.equalTo(54)
        })
        self.cancelButton?.layer.cornerRadius = 27
        self.cancelButton?.backgroundColor = color("#F5F6F8")
        self.cancelButton?.setTitle("返回", for: .normal)
        self.cancelButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.cancelButton?.setTitleColor(.black, for: .normal)
        self.cancelButton?.addTarget(self, action: #selector(backAction), for: .touchUpInside)
        
        self.confirmButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.confirmButton!)
        self.confirmButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.bottomContainerView!.snp.centerX).offset(5)
            make.right.equalTo(self.bottomContainerView!).offset(-12)
            make.height.equalTo(54)
            make.centerY.equalTo(self.bottomContainerView!)
        })
        self.confirmButton?.setTitle("确定", for: .normal)
        self.confirmButton?.backgroundColor = color("#FA6161")
        self.confirmButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.confirmButton?.setTitleColor(.white, for: .normal)
        self.confirmButton?.layer.cornerRadius = 27
        self.confirmButton?.addTarget(self, action: #selector(addAddressAction), for: .touchUpInside)
        
        self.contentContainerView = UIView()
        self.view.addSubview(self.contentContainerView!)
        self.contentContainerView?.snp.makeConstraints({ make in
            make.left.equalTo(self.view).offset(12)
            make.right.equalTo(self.view).offset(-12)
            make.top.equalTo(self.view).offset(16+statusBarHeight+44)
            make.height.equalTo(288)
        })
        self.contentContainerView?.backgroundColor = .white
        self.contentContainerView?.layer.cornerRadius = 8
        
        let usernameLeftView = JDStarTitle()
        usernameLeftView.frame = CGRect(x: 0, y: 0, width: 70, height: 55)
        self.contentContainerView?.addSubview(usernameLeftView)
        usernameLeftView.snp.makeConstraints { make in
            make.left.equalTo(self.contentContainerView!).offset(12)
            make.top.equalTo(self.contentContainerView!)
            make.size.equalTo(CGSize(width: 70, height: 55))
        }
        usernameLeftView.titleLabel?.text = "用户名称"
        usernameLeftView.backgroundColor = .white
        usernameLeftView.addBottomLine()
        
        self.usernameInputView = UITextField()
        self.contentContainerView?.addSubview(self.usernameInputView!)
        self.usernameInputView?.snp.makeConstraints({ make in
            make.left.equalTo(self.contentContainerView!).offset(12+70)
            make.right.equalTo(self.contentContainerView!).offset(-12)
            make.top.equalTo(self.contentContainerView!)
            make.height.equalTo(55)
        })
        self.usernameInputView?.backgroundColor = .white
        self.usernameInputView?.placeholder = "请输入"
        self.usernameInputView?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.usernameInputView?.textColor = color("#333333")
        self.usernameInputView?.textAlignment = .right
        self.usernameInputView?.addBottomLine()
        
        let phoneNumLeftView = JDStarTitle()
        phoneNumLeftView.frame = CGRect(x: 0, y: 0, width: 70, height: 55)
        self.contentContainerView?.addSubview(phoneNumLeftView)
        phoneNumLeftView.snp.makeConstraints { make in
            make.left.equalTo(self.contentContainerView!).offset(12)
            make.top.equalTo(usernameLeftView.snp.bottom)
            make.size.equalTo(CGSize(width: 70, height: 55))
        }
        phoneNumLeftView.titleLabel?.text = "联系电话"
        phoneNumLeftView.backgroundColor = .white
        phoneNumLeftView.addBottomLine()
        
        self.phoneNumInputView = UITextField()
        self.contentContainerView?.addSubview(self.phoneNumInputView!)
        self.phoneNumInputView?.snp.makeConstraints({ make in
            make.left.equalTo(self.contentContainerView!).offset(12+70)
            make.right.equalTo(self.contentContainerView!).offset(-12)
            make.top.equalTo(self.usernameInputView!.snp.bottom)
            make.height.equalTo(55)
        })
        self.phoneNumInputView?.backgroundColor = .white
        self.phoneNumInputView?.placeholder = "请输入"
        self.phoneNumInputView?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.phoneNumInputView?.textColor = color("#333333")
        self.phoneNumInputView?.textAlignment = .right
        self.phoneNumInputView?.addBottomLine()
        
        let selectedAddressLeftView = JDStarTitle()
        selectedAddressLeftView.frame = CGRect(x: 0, y: 0, width: 70, height: 55)
        self.contentContainerView?.addSubview(selectedAddressLeftView)
        selectedAddressLeftView.snp.makeConstraints { make in
            make.left.equalTo(self.contentContainerView!).offset(12)
            make.top.equalTo(phoneNumLeftView.snp.bottom)
            make.size.equalTo(CGSize(width: 70, height: 55))
        }
        selectedAddressLeftView.titleLabel?.text = "省/市/区"
        selectedAddressLeftView.backgroundColor = .white
        selectedAddressLeftView.addBottomLine()
        
        self.selectedAddressInputView = UITextField()
        self.contentContainerView?.addSubview(self.selectedAddressInputView!)
        self.selectedAddressInputView?.snp.makeConstraints({ make in
            make.left.equalTo(self.contentContainerView!).offset(12+70)
            make.right.equalTo(self.contentContainerView!).offset(-12)
            make.top.equalTo(self.phoneNumInputView!.snp.bottom)
            make.height.equalTo(55)
        })
        self.selectedAddressInputView?.backgroundColor = .white
        self.selectedAddressInputView?.placeholder = "请输入"
        self.selectedAddressInputView?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.selectedAddressInputView?.textColor = color("#333333")
        self.selectedAddressInputView?.textAlignment = .right
        self.selectedAddressInputView?.addBottomLine()
//        self.selectedAddressInputView?.isEnabled = false
//        self.selectedAddressInputView?.isUserInteractionEnabled = true
       
        
        let detailTitle = JDStarTitle()
        detailTitle.frame = CGRect(x: 0, y: 0, width: 70, height: 20)
        self.contentContainerView?.addSubview(detailTitle)
        detailTitle.snp.makeConstraints { make in
            make.left.equalTo(self.contentContainerView!).offset(12)
            make.top.equalTo(selectedAddressLeftView.snp.bottom).offset(20)
            make.height.equalTo(20)
        }
        detailTitle.titleLabel?.text = "详细地址"
        
        self.detailAddressInputView = UITextView()
        self.contentContainerView?.addSubview(self.detailAddressInputView!)
        self.detailAddressInputView?.snp.makeConstraints({ make in
            make.left.equalTo(self.contentContainerView!).offset(7)
            make.top.equalTo(detailTitle.snp.bottom)
            make.right.equalTo(self.contentContainerView!).offset(-7)
            make.bottom.equalTo(self.contentContainerView!).offset(-5)
        })
        self.detailAddressInputView?.placeholder = "请输入"
        self.detailAddressInputView?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        
        
        self.contentContainerView?.layoutSubviews()
        
        self.selectedAddressControl = UIControl(frame: .init(x: 0, y: 0, width: screenWidth - 70-24-24, height: 55))
        self.selectedAddressInputView?.addSubview(self.selectedAddressControl!)
        self.selectedAddressControl?.addTarget(self, action: #selector(selectedAddressAction), for: .touchUpInside)
        
        self.switchButton = UISwitch()
        self.view.addSubview(self.switchButton!)
        self.switchButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.view).offset(-24)
            make.top.equalTo(self.contentContainerView!.snp.bottom).offset(15)
            make.size.equalTo(CGSizeMake(48, 28))
        })
        self.switchButton?.onTintColor = color("#FA6161")
        self.switchButton?.thumbTintColor = .white
        
        self.switchTitleLabel = UILabel()
        self.view.addSubview(self.switchTitleLabel!)
        self.switchTitleLabel?.snp.makeConstraints({ make in
            make.centerY.equalTo(self.switchButton!)
            make.right.equalTo(self.switchButton!.snp.left).offset(-8)
        })
        self.switchTitleLabel?.text = "设置默认地址"
        self.switchTitleLabel?.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"))
        
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    @objc func selectedAddressAction() {
        self.view.endEditing(true)
        printLog("选择地址")
        if self.addressPickerView == nil {
            self.addressPickerView = JDAddressPickerView()
            self.addressPickerView?.myDelegate = self
        }
        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(addressPickerView!.view)
        self.addressPickerView?.showPickerView()
    }
    
    @objc func addAddressAction() {
        
        if !(self.phoneNumInputView?.text?.verificationMobile() ?? false) {
            self.view.toast(message: "请输入正确的手机号码")
            return
        }
        
        if (self.usernameInputView?.text?.count ?? 0) <= 0 {
            self.view.toast(message: "请输入用户名称")
            return
        }
        
        if (self.selectedAddressInputView?.text?.count ?? 0) <= 0 {
            self.view.toast(message: "请选择所在城市")
            return
        }
        
        if (self.detailAddressInputView?.text.count ?? 0) <= 0 {
            self.view.toast(message: "请输入详细地址")
            return
        }
        
        var params = [String: Any]()
        // 1是 0不是 默认
        params["defaultFlag"] = (self.switchButton?.isOn ?? false) ? 1 : 0
        params["receiverName"] = self.usernameInputView?.text
        params["mobile"] = self.phoneNumInputView?.text
        // 邮编
        params["postal"] = "116000"
        self.showLoading()
        if self.type == 0 {
            printLog("新增收货地址")
            
            // 省份
            params["province"] = self.addressPickerView?.provinceName
            // 城市
            params["city"] = self.addressPickerView?.cityName
            // 区/街道
            params["district"] = self.addressPickerView?.areaName
            // 详细地址
            params["address"] = self.detailAddressInputView?.text
            
            JDNetWorkRequest(.saveAddress(params)) { responseStr in
                printLog("新增收货地址:\(responseStr)")
                self.dismissLoading()
                let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                if commonModel?.code == "0" {
                    self.addressChangeCallback?(true)
                    // 成功
                    self.navigationController?.popViewController(animated: true)
                    
                } else if commonModel?.code == "401" {
                    // 未登录
                }
            } failure: { error in
                self.addressChangeCallback?(false)
                self.dismissLoading()
                printLog("错误:\(error)")
            } error: { errorCode in
                self.addressChangeCallback?(false)
                self.dismissLoading()
                printLog("失败code:\(errorCode)")
            }
        } else {
            printLog("编辑/更新")
            
            params["id"] = self.addressModel?.id
            
            if (self.addressPickerView?.provinceName?.count ?? 0) <= 0 {
                // 省份
                params["province"] = self.addressModel?.province
            } else {
                // 省份
                params["province"] = self.addressPickerView?.provinceName
            }
            
            if (self.addressPickerView?.cityName?.count ?? 0) <= 0 {
                // 城市
                params["city"] = self.addressModel?.city
            } else {
                // 城市
                params["city"] = self.addressPickerView?.cityName
            }
            
            if (self.addressPickerView?.areaName?.count ?? 0) <= 0 {
                // 区/街道
                params["district"] = self.addressModel?.district
            } else {
                // 区/街道
                params["district"] = self.addressPickerView?.areaName
            }
            
            if (self.detailAddressInputView?.text.count ?? 0) <= 0 {
                // 详细地址
                params["address"] = self.addressModel?.address
            } else {
                // 详细地址
                params["address"] = self.detailAddressInputView?.text
            }
            
            printLog("参数:\(params)")
            
            JDNetWorkRequest(.updateAddress(params)) { responseStr in
                
                printLog("更新收货地址:\(responseStr)")
                self.dismissLoading()
                let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                if commonModel?.code == "0" {
                    // 成功
                    self.addressChangeCallback?(true)
                    self.navigationController?.popViewController(animated: true)
                    
                } else if commonModel?.code == "401" {
                    // 未登录
                }
                
            } failure: { error in
                self.addressChangeCallback?(false)
                self.dismissLoading()
                printLog("更新错误:\(error)")
            } error: { errorCode in
                self.addressChangeCallback?(false)
                self.dismissLoading()
                printLog("更新失败code:\(errorCode)")
            }
            
        }
        
    }

}

class JDStarTitle: UIView {
    
    var titleLabel: UILabel?
    var starLabel: UILabel?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUIElements()
    }
    
    func setupUIElements() {
        self.titleLabel = UILabel()
        self.addSubview(self.titleLabel!)
        self.titleLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self)
            make.centerY.equalTo(self)
        })
        self.titleLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#8D9198"))
        self.titleLabel?.text = "联系电话 "
        
        self.starLabel = UILabel()
        self.addSubview(self.starLabel!)
        self.starLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.titleLabel!.snp.right)
            make.centerY.equalTo(self.titleLabel!).offset(-2)
        })
        self.starLabel?.text = "*"
        self.starLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#FA6161"))
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension JDAddAddressViewController: JDAddressPickerViewDelegate {
    func selectAddressFinish() {
        let detailAddressString = String.init(format: "%@ %@ %@", self.addressPickerView?.provinceName ?? "", self.addressPickerView?.cityName ?? "", self.addressPickerView?.areaName ?? "")

        self.selectedAddressInputView?.text = detailAddressString
    }
}
